/*
 * @Author: wangtao
 * @Date: 2020-06-29 16:32:41
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-29 17:25:18
 * @Description: file content
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Modal,
  Text,
  TouchableOpacity,
  PixelRatio,
  TextInput,
  Keyboard,
  ScrollView,
  NativeModules,
} from 'react-native';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  fontColorBlack,
  fontColorCoffee,
  screenWidth,
  px2dp,
  screenHeight,
  splitLineColorLightGray,
  fontColorSecDeepGray,
  fontColorDeepGray,
  fontColorLightCoffee,
} from '@/styles';
import { Button, msg } from '@/common';
import { uploadImage, uploadVideo } from '@/config';
import api from '@/api';
import { UploadImgs } from '@/components';

const { Submit } = Button;

export default class ApplyLeave extends Component {
  constructor(props) {
    super(props);
    this.state = {
      type: 2, // 状态1车辆 2司机
      state: null, // 状态1销假  2请假
      remark: '', // 原因
      pics: [], // 请假图片
      picsParams: [], // 请假图片提交参数
      keyboardHeight: '', // 键盘高度
      isSubmit: false
    };
  }

  componentDidMount() {
    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  render() {
    const { onChangeModal } = this.props;
    const { type, remark, pics, isSubmit } = this.state;
    return (
      <Modal
        animationType='slide'
        transparent
        visible
        onRequestClose={() => {
          onChangeModal({ type: 'applyLeaveModelIsShow', val: false });
          // msg.emit('router: back');
        }}
        onShow={() => { }}
      >
        <TouchableOpacity
          style={styles.mask}
          onPress={() => {
            onChangeModal({ type: 'applyLeaveModelIsShow', val: false });
          }}
        />
        <View
          style={[
            styles.infoContainer,
            { marginBottom: Number(this.state.keyboardHeight) },
          ]}
        >
          <View style={styles.header}>
            <TouchableOpacity
              style={styles.cancel}
              onPress={() => {
                onChangeModal({ type: 'applyLeaveModelIsShow', val: false });
              }}
            >
              <Text style={{ fontSize: px2dp(32), color: fontColorSecDeepGray }}>
                取消
              </Text>
            </TouchableOpacity>
            <Text
              style={{
                fontSize: px2dp(32),
                color: fontColorBlack,
                fontWeight: 'bold',
              }}
            >
              申请请假
            </Text>
            <Submit
              text='确定'
              boxStyle={{
                width: px2dp(104),
                height: px2dp(60),
                borderRadius: px2dp(8),
                backgroundColor: mainBgColorWhite,
                position: 'absolute',
                right: px2dp(28),
              }}
              btnTextStyle={{
                fontSize: px2dp(32),
                color: fontColorCoffee,
              }}
              disabled={false}
              onClick={() => {
                this.submit();
              }}
            />
          </View>
          {/* 备注 */}
          <ScrollView
            style={styles.editContainer}
            showsVerticalScrollIndicator={false}
          >
            <View style={styles.typeSelectContainer}>
              <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => {
                  this.setState({ type: 2 });
                }}
              >
                <Text style={[styles.typeSelect, type === 2 ? styles.typeSelectActive : {}]}>
                  司机请假
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => {
                  this.setState({ type: 1 });
                }}
              >
                <Text style={[styles.typeSelect, type === 1 ? styles.typeSelectActive : {}]}>
                  车辆维修保养
                </Text>
              </TouchableOpacity>
            </View>
            <Text style={styles.title}>
              原因描述
              <Text style={[(!isSubmit || remark.length < 0)
                ? { color: fontColorSecDeepGray }
                : { color: 'red' }, { fontWeight: 'normal' }]}
              >
                (必填)
              </Text>
            </Text>
            <View style={styles.inputContent}>
              <TextInput
                style={[
                  styles.goodsWrapPriceTextInput,
                  { color: fontColorBlack },
                ]}
                placeholder='请输入请假事由'
                placeholderTextColor='#CDCCC9'
                multiline
                maxLength={100}
                defaultValue=''
                value={remark}
                underlineColorAndroid='transparent'
                onChangeText={(text) => {
                  this.onChangeText(text);
                }}
                onBlur={() => { }}
              />
              <View style={styles.textNumWarp}>
                <Text style={styles.textNum}>
                  {remark ? remark.length : 0}
                  /50
                </Text>
              </View>
            </View>

            <View style={styles.packing}>
              <Text style={styles.title}>
                图片/视频
                <Text
                  style={{ color: fontColorSecDeepGray, fontWeight: 'normal' }}
                >
                  (选填，最多4张)
                </Text>
              </Text>
              <UploadImgs
                length={4}
                mr={{ marginRight: px2dp(15) }}
                lineLength={4}
                uploadImage={() => this._selectImg('pics')}
                picDelete={(i, index) => this.deletImg(i, index)}
                picData={pics}
              />
            </View>
          </ScrollView>
        </View>
      </Modal>
    );
  }

  // 删除
  deletImg = (i, index) => {
    console.log('🚀🚀🚀wimi======>>>i,index', i, index);
    const { pics, picsParams } = this.state;
    pics.splice(index, 1);
    picsParams.splice(index, 1);
    this.setState({ pics, picsParams });
  }

  // 选择照片
  _selectImg = (type) => {
    NativeModules.DataModule.chooseImageOrVideo((path, imageBase64, resType, mimeName) => {
      console.log('🚀🚀🚀wimi======>>>resType', resType);
      if (resType == 'video') {
        this.uploadVideo(path, type, imageBase64, resType, mimeName);
      } else {
        this.upload(path, type, imageBase64, resType);
      }
    });
  };

  // 上传照片
  upload(path, type, imageBase64, resType) {
    NativeModules.WindowModule.showLoading();
    uploadImage('upload?dirName=driverLeave', path)
      .then((res) => {
        console.log('🚀🚀🚀wimi======>>>res', JSON.stringify(res));
        // 请求成功
        if (res.success) {
          this.onChange(type, res.data.localId, imageBase64, resType);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => { },
          );
          // 服务器返回异常，设定服务器返回的异常信息保存在 header.msgArray[0].desc
          console.log('--->', res.header.msgArray[0].desc);
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        console.log(err);
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => { },
        );
      });
  }

  // 上传视频
  uploadVideo(path, type, imageBase64, resType, mimeName) {
    NativeModules.WindowModule.showLoading();
    uploadVideo('upload?dirName=driverLeave', mimeName, path)
      .then((res) => {
        console.log('🚀🚀🚀wimi======>>>res', JSON.stringify(res));
        // 请求成功
        if (res.success) {
          this.onChange(type, res.data.localId, imageBase64, resType);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => { },
          );
          // 服务器返回异常，设定服务器返回的异常信息保存在 header.msgArray[0].desc
          console.log('--->', res.header.msgArray[0].desc);
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        console.log(err);
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => { },
        );
      });
  }

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }

  // 改变
  onChangeText = (text) => {
    if (text.length > 50) {
      return;
    }
    this.setState({ remark: text });
  };

  // 改变
  onChange = (type, val, imageBase64, resType) => {
    if (type === 'pics') {
      const { pics } = this.state;
      if (resType == 'video') {
        pics.push({ imageBase64: `data:image/jpeg;base64,${imageBase64}`, localId: val, type: resType });
        this.state.picsParams.push({ fileType: 2, fileUrl: val });
      } else {
        pics.push({ imageBase64: `data:image/jpeg;base64,${imageBase64}`, localId: val, type: resType });
        this.state.picsParams.push({ fileType: 1, fileUrl: val });
      }

      this.setState({ pics });
    } else {
      this.setState({ [type]: val });
    }
  };

  // 提交
  submit = () => {
    const { type, remark, picsParams } = this.state;
    const { onChangeModal } = this.props;
    if (!remark) {
      this.setState({ isSubmit: true });
      return;
    }
    api.supply.updateDriverState({
      type,
      state: 2, // 1销假 2请假
      remark: remark,
      pics: picsParams,
    }).then((res) => {
      if (res.success) {
        onChangeModal({ type: 'applyLeaveModelIsShow', val: false });
        msg.emit('router: refreshRoute', {
          routeName: 'DriverTab',
        });
      } else {
        msg.emit('router: refreshRoute', {
          routeName: 'DriverTab',
        });
        msg.emit('app:tip', { text: '请假失败' });
      }
    });
  };
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    position: 'absolute',
    left: 0,
    top: 0,
  },
  infoContainer: {
    width: screenWidth,
    maxHeight: 0.5 * screenHeight,
    backgroundColor: mainBgColorWhite,
    position: 'absolute',
    bottom: 0,
    left: 0,
    borderRadius: px2dp(12),
    overflow: 'hidden',
    zIndex: 10,
  },
  header: {
    width: screenWidth,
    height: px2dp(108),
    justifyContent: 'center',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderColor: splitLineColorLightGray,
  },
  cancel: {
    position: 'absolute',
    left: 0,
    top: 0,
    width: 80,
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },

  packingSelect: {
    marginTop: px2dp(24),
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'flex-start',
  },
  selectItem: {
    width: px2dp(218),
    height: px2dp(72),
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(8),
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: px2dp(16),
    marginRight: px2dp(10),
  },
  editContainer: {
    paddingHorizontal: px2dp(32),
  },
  inputContent: {
    marginTop: px2dp(24),
    paddingHorizontal: 12,
    paddingVertical: 12,
    backgroundColor: mainBgColorLightGray,
  },
  goodsWrapPriceTextInput: {
    fontSize: px2dp(32),
    height: px2dp(160),
    width: '100%',
    backgroundColor: mainBgColorLightGray,
    textAlignVertical: 'top',
  },
  textNumWarp: {
    flex: 1,
    justifyContent: 'flex-end',
    flexDirection: 'row',
  },
  textNum: {
    color: 'rgb(153,153,153)',
    fontSize: 14,
  },
  title: {
    fontSize: px2dp(28),
    color: fontColorBlack,
    fontWeight: 'bold',
    marginTop: px2dp(40),
  },
  typeSelectContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: px2dp(32)
  },
  typeSelect: {
    width: px2dp(330),
    height: px2dp(80),
    backgroundColor: mainBgColorLightGray,
    fontSize: px2dp(28),
    color: fontColorDeepGray,
    textAlign: 'center',
    lineHeight: px2dp(80),
    borderRadius: px2dp(8)
  },
  typeSelectActive: {
    borderWidth: 1 / PixelRatio.get(),
    borderColor: fontColorCoffee,
    backgroundColor: fontColorLightCoffee,
    color: fontColorCoffee,
    fontWeight: '600'
  },
});
